package com.example.administrator.myapplication.ex;

import android.content.Context;

public class AppExceptionHandle implements Thread.UncaughtExceptionHandler {


    private Thread.UncaughtExceptionHandler mExHandle;

    private static AppExceptionHandle appExceptionHandle = new AppExceptionHandle();

    private Context context;

    private ExceptionListener exceptionListener;

    /**
     * //保护单例
     */
    private AppExceptionHandle() {
    }

    /**
     * 外部获取
     *
     * @return AppExceptionHandle
     */
    public static synchronized AppExceptionHandle getInstance() {
        if (null == appExceptionHandle) {
            return new AppExceptionHandle();
        }
        return appExceptionHandle;
    }

    public void init(Context context,ExceptionListener listener) {
        this.mExHandle = Thread.getDefaultUncaughtExceptionHandler(); //保存系统默认的处理器
        Thread.setDefaultUncaughtExceptionHandler(this);//设置本处理器为系统异常处理器
        this.context = context; //关联上下文
        this.exceptionListener = listener;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        //异常的捕获处理
        exceptionListener.before();
        boolean fix = exceptionListener.fix(thread, throwable, context);
        exceptionListener.after();
        if (!fix) {
            mExHandle.uncaughtException(thread, throwable);
        }
    }

    public ExceptionListener getExceptionListener() {
        return exceptionListener;
    }

}
